﻿using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

namespace ZSW.Framework.Utils
{
    public static class ZSWFUtil_UI
    {
        public static void SetText(Text t, string content)
        {
            t.text = content;
        }

        public static void SetColor(Text t, Color color)
        {
            t.color = color;
        }

        public static void SetSprite(Image i, Sprite sprite)
        {
            i.sprite = sprite;
        }

        public static void SetAlpha(Image i, float alpha)
        {
            Color c = i.color;
            c.a = alpha;
            i.color = c;
        }
        public static void AddAlpha(Image i, float alpha)
        {
            Color c = i.color;
            c.a += alpha;
            i.color = c;
        }
        public static void SubAlpha(Image i, float alpha)
        {
            Color c = i.color;
            c.a -= alpha;
            i.color = c;
        }

        public static IEnumerator fadeIn(CanvasGroup canvasGroup, float fadeTime, Action callback = null)
        {
            float alpha_step = 1f / fadeTime;
            while (canvasGroup.alpha < 1)
            {
                canvasGroup.alpha += alpha_step * UnityEngine.Time.deltaTime;
                yield return null;
            }
            canvasGroup.alpha = 1f;
            callback?.Invoke();
        }
        public static IEnumerator fadeOut(CanvasGroup canvasGroup, float fadeTime, Action callback = null)
        {
            float alpha_step = 1f / fadeTime;
            while (canvasGroup.alpha > 0)
            {
                canvasGroup.alpha -= alpha_step * UnityEngine.Time.deltaTime;
                yield return null;
            }
            canvasGroup.alpha = 0f;
            callback?.Invoke();
        }
        public static Image GenerateImage(Sprite sprite, Transform parent)
        {
            GameObject obj = new GameObject("Image");
            obj.AddComponent<CanvasRenderer>();
            Image img = obj.AddComponent<Image>();
            img.color = Color.white;
            img.sprite = sprite;
            obj.transform.SetParent(parent);
            return img;
        }
    }
}